package com.zdy.viewpager;

import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItem;

import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import in.srain.cube.views.ptr.header.RentalsSunHeaderView;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

public class RentalsStyleFragment extends Fragment {

	private String mUrl = "http://img4.duitang.com/uploads/blog/201407/07/20140707113856_hBf3R.thumb.jpeg";
	private long mStartLoadingTime = -1;
	private boolean mImageHasLoaded = false;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View view = inflater.inflate(R.layout.fragment_materail_style, null);
		// setHeaderTitle(R.string.ptr_demo_rentals_style);
		int position = FragmentPagerItem.getPosition(getArguments());
		TextView title = (TextView) view.findViewById(R.id.item_title);
		title.setText(String.valueOf(position));
		final ImageView imageView = (ImageView) view
				.findViewById(R.id.material_style_image_view);

		final PtrFrameLayout frame = (PtrFrameLayout) view
				.findViewById(R.id.material_style_ptr_frame);

		// header
		final RentalsSunHeaderView header = new RentalsSunHeaderView(
				getActivity());
		header.setLayoutParams(new PtrFrameLayout.LayoutParams(-1, -2));
		// header.setPadding(0, LocalDisplay.dp2px(15), 0,
		// LocalDisplay.dp2px(10));
		header.setUp(frame);

		frame.setLoadingMinTime(1000);
		frame.setDurationToCloseHeader(500);
		frame.setHeaderView(header);
		frame.addPtrUIHandler(header);
		// frame.setPullToRefresh(true);
		frame.postDelayed(new Runnable() {
			@Override
			public void run() {
				frame.autoRefresh(true);
			}
		}, 100);

		frame.setPtrHandler(new PtrHandler() {
			@Override
			public boolean checkCanDoRefresh(PtrFrameLayout frame,
					View content, View header) {
				return true;
			}

			@Override
			public void onRefreshBegin(final PtrFrameLayout frame) {
				if (mImageHasLoaded) {
					long delay = 1500;
					frame.postDelayed(new Runnable() {
						@Override
						public void run() {
							frame.refreshComplete();
						}
					}, delay);
				} else {
					mStartLoadingTime = System.currentTimeMillis();
				}
			}
		});

		long delay = 1500;
		frame.postDelayed(new Runnable() {
			@Override
			public void run() {
				mImageHasLoaded = true;
				imageView.setImageResource(R.drawable.sky);
				frame.refreshComplete();
			}
		}, delay);

		return view;
	}
}
